import { defineComponent, ref, reactive, onMounted } from 'vue';
import { Button, Modal, Steps, Table, Tag, Space, message, Tooltip } from 'ant-design-vue';
import { CheckCircleOutlined, CloseCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { cloneDeep } from 'lodash-es';
import modeler from '@/store/modules/modeler';
import { taskAttr } from '@/store/modules/taskAttr';
import { processInfo } from '@/store/modules/processInfo';

interface CheckResult {
  id: string;
  type: 'error' | 'warning' | 'info';
  message: string;
  elementId: string;
  elementName: string;
  location?: string;
}

interface FlowStep {
  title: string;
  description: string[];
}

interface ProcessCheckProps {
  processInfo: any;
  onCheckStart?: () => void;
  onCheckComplete?: (results: CheckResult[]) => void;
}

export default defineComponent({
  name: 'BpmnProcessCheck',
  props: {
    processInfo: {
      type: Object as PropType<any>,
      required: true
    },
    onCheckStart: {
      type: Function as PropType<() => void>,
      default: () => {}
    },
    onCheckComplete: {
      type: Function as PropType<(results: CheckResult[]) => void>,
      default: () => {}
    }
  },
  setup(props) {
    const visible = ref(false);
    const loading = ref(false);
    const checkResults = ref<CheckResult[]>([]);
    const flowSteps = ref<FlowStep[]>([]);
    const stepStatus = ref<'process' | 'success' | 'error' | 'warning'>('process');
    const flowStepsCurrent = ref(0);
    const totalErrors = ref(0);
    const totalWarnings = ref(0);
    const totalInfos = ref(0);

    const modelerStore = modeler();
    const taskAttrStore = taskAttr();
    const processInfoStore = processInfo();
    
    // 表格列定义
    const columns = [
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 80,
        render: (type: string) => {
          const tagMap = {
            error: { color: 'red', text: '错误' },
            warning: { color: 'orange', text: '警告' },
            info: { color: 'blue', text: '提示' }
          };
          const tag = tagMap[type] || { color: 'gray', text: '未知' };
          return <Tag color={tag.color}>{tag.text}</Tag>;
        }
      },
      {
        title: '元素',
        dataIndex: 'elementName',
        key: 'elementName',
        width: 150,
        render: (text: string, record: CheckResult) => (
          <Tooltip title={record.elementId}>
            <span>{text || record.elementId}</span>
          </Tooltip>
        )
      },
      {
        title: '位置',
        dataIndex: 'location',
        key: 'location',
        width: 120
      },
      {
        title: '描述',
        dataIndex: 'message',
        key: 'message',
        flex: 1
      },
      {
        title: '操作',
        key: 'action',
        width: 80,
        render: (_, record: CheckResult) => (
          <Button 
            type="link" 
            size="small"
            onClick={() => navigateToElement(record.elementId)}
          >
            定位
          </Button>
        )
      }
    ];
    
    const addCheckResult = (result: CheckResult) => {
      checkResults.value.push(result);
      
      if (result.type === 'error') {
        totalErrors.value++;
      } else if (result.type === 'warning') {
        totalWarnings.value++;
      } else if (result.type === 'info') {
        totalInfos.value++;
      }
    };
    
    const navigateToElement = (elementId: string) => {
      try {
        const modeler = modelerStore.getModeler;
        if (!modeler) return;
        
        // 获取画布和元素
        const canvas = modeler.get('canvas');
        const elementRegistry = modeler.get('elementRegistry');
        
        // 查找元素
        const element = elementRegistry.get(elementId);
        if (element) {
          canvas.zoom('fit-viewport', element);
          modeler.get('selection').select(element);
          
          visible.value = false;
        } else {
          message.warning('无法定位到指定元素');
        }
      } catch (error) {
        console.error('定位元素失败:', error);
        message.error('定位元素失败');
      }
    };
    
    // 获取开始任务
    const getStartTask = (elementRegistry: any) => {
      const elements = elementRegistry.getAll();
      return elements.find((element: any) => element.type === 'bpmn:StartEvent');
    };
    
    // 查找下一个用户任务
    const findNextUserTask = (element: any, elementRegistry: any) => {
      const result: any[] = [];
      
      if (!element.outgoing || element.outgoing.length === 0) {
        return result;
      }
      
      for (const outgoing of element.outgoing) {
        const target = outgoing.target;
        if (target.type === 'bpmn:UserTask') {
          result.push(target);
        } else {
          result.push(...findNextUserTask(target, elementRegistry));
        }
      }
      
      return result;
    };
    
    // 获取后续节点
    const getSubsequentNodes = (element: any, elementRegistry: any) => {
      const result: any[] = [];
      const visited = new Set();
      
      const traverse = (currentElement: any) => {
        if (!currentElement || visited.has(currentElement.id)) {
          return;
        }
        
        visited.add(currentElement.id);
        result.push(currentElement);
        
        if (currentElement.outgoing) {
          for (const outgoing of currentElement.outgoing) {
            if (outgoing.target) {
              traverse(outgoing.target);
            }
          }
        }
      };
      
      traverse(element);
      return result;
    };
    
    // 递归检查后续节点
    const getNextNodeStep = (element: any, elementRegistry: any) => {
      // 判断是不是结束
      if (element.type === 'bpmn:EndEvent') {
        return;
      }
      
      // 1.如果没有出口
      if (element.outgoing?.length === 0) {
        if (element.type === 'bpmn:SequenceFlow') {
          const flowTarget = element.target;
          if (flowTarget) {
            return getNextNodeStep(flowTarget, elementRegistry);
          }
        } else if (['bpmn:ExclusiveGateway', 'bpmn:InclusiveGateway', 'bpmn:ParallelGateway'].includes(element.type)) {
          const gateWayTarget = element.outgoing;
          if (gateWayTarget && gateWayTarget.length > 0) {
            return getNextNodeStep(gateWayTarget[0], elementRegistry);
          }
        }
        
        // 错误：流程没有设置结束事件节点
        addCheckResult({
          type: 'error',
          message: '流程没有设置结束事件节点',
          elementId: element.id,
          elementName: element.businessObject.name || element.id
        });
        
        // 添加错误步骤
        flowSteps.value.push({
          title: '检查失败',
          description: ['错误：流程没有设置结束事件节点']
        });
        
        stepStatus.value = 'error';
        flowStepsCurrent.value++;
        
        // 添加后续节点为未检查状态
        const subsequentNodes = getSubsequentNodes(element, elementRegistry);
        subsequentNodes.forEach(item => {
          flowSteps.value.push({
            title: item.businessObject.name || item.id,
            description: ['检查未开始']
          });
        });
        
        return;
      }
      
      // 2.如果只有一个出口
      else if (element.outgoing?.length === 1) {
        // 判断是不是结束
        if (element.type === 'bpmn:EndEvent') {
          flowSteps.value.push({
            title: '结束',
            description: ['流程设计：检查完毕']
          });
          stepStatus.value = 'process';
          flowStepsCurrent.value++;
          return;
        }
        
        // 判断是不是线
        else if (element.type === 'bpmn:SequenceFlow') {
          const flowTarget = element.target;
          if (flowTarget) {
            return getNextNodeStep(flowTarget, elementRegistry);
          }
        }
        
        // 判断是不是网关
        else if (['bpmn:ExclusiveGateway', 'bpmn:InclusiveGateway', 'bpmn:ParallelGateway'].includes(element.type)) {
          const gateWayTarget = element.outgoing[0];
          if (gateWayTarget) {
            return getNextNodeStep(gateWayTarget, elementRegistry);
          }
        }
        
        // 普通任务节点检查
        else {
          console.log(element, "11111111111111");
          
          // 获取任务配置信息
          const task = taskAttrStore.tasks.find(
            item => item.TASK_NODE_NO === element.id
          );
          
          const desc = ['1.流程设计：检查完毕。'];
          let hasError = false;
          
          // 检查处理人设置
          if ((task?.TASK_RUN_DATA == null || task?.TASK_RUN_DATA === "") && task?.TASK_NODE_NAME !== "起草节点") {
            desc.push("2.处理人设置为空。");
            addCheckResult({
              type: 'warning',
              message: '处理人设置为空',
              elementId: element.id,
              elementName: element.businessObject.name || element.id
            });
            hasError = true;
          }
          
          // 检查节点表单设置
          if (task?.TASK_NODE_FORM == null || task?.TASK_NODE_FORM === "") {
            desc.push("3.节点表单未设置。");
            addCheckResult({
              type: 'warning',
              message: '节点表单未设置',
              elementId: element.id,
              elementName: element.businessObject.name || element.id
            });
            hasError = true;
          }
          
          // 添加节点检查步骤
          flowSteps.value.push({
            title: `节点：${element.businessObject.name || element.id}`,
            description: desc
          });
          
          stepStatus.value = hasError ? 'warning' : 'process';
          flowStepsCurrent.value++;
          
          // 继续检查下一个节点
          if (element.outgoing[0]) {
            return getNextNodeStep(element.outgoing[0], elementRegistry);
          }
        }
      }
      
      // 网关节点（多个出口）
      else if (element.outgoing?.length > 1) {
        // 添加网关检查步骤
        flowSteps.value.push({
          title: `网关：${element.businessObject.name || element.id}`,
          description: ['流程设计：检查完成']
        });
        
        stepStatus.value = 'process';
        flowStepsCurrent.value++;
        
        // 递归检查所有分支
        for (const sequenceFlow of element.outgoing) {
          getNextNodeStep(sequenceFlow, elementRegistry);
        }
      }
    };
    
    // 执行流程检查
    const runProcessCheck = async () => {
      if (loading.value) return;
      
      loading.value = true;
      props.onCheckStart();
      
      try {
        checkResults.value = [];
        flowSteps.value = [];
        stepStatus.value = 'process';
        flowStepsCurrent.value = 0;
        totalErrors.value = 0;
        totalWarnings.value = 0;
        totalInfos.value = 0;
        
        const modeler = modelerStore.getModeler;
        if (!modeler) {
          throw new Error('无法获取流程模型');
        }
        
        const elementRegistry = modeler.get('elementRegistry');
        if (!elementRegistry) {
          throw new Error('无法获取元素注册表');
        }
        
        // 添加开始步骤
        flowSteps.value.push({
          title: '开始',
          description: ['1.流程设计：检查中', '2.获取开始节点']
        });
        
        // 获取启动节点
        const startTask = getStartTask(elementRegistry);
        if (!startTask) {
          throw new Error('未找到开始节点');
        }
        
        // 更新开始步骤状态
        flowSteps.value[0].description = ['1.流程设计：检查完毕', '2.获取开始节点：成功'];
        
        // 查找第一个用户任务
        const firstUserTask = findNextUserTask(startTask, elementRegistry);
        
        // 检查开始节点后续节点数量
        if (firstUserTask.length > 1) {
          // 错误：开始事件节点后面有且只有一个节点
          addCheckResult({
            type: 'error',
            message: '开始事件节点后面有且只能有一个节点',
            elementId: startTask.id,
            elementName: startTask.businessObject.name || '开始节点'
          });
          
          // 添加错误步骤
          flowSteps.value.push({
            title: '检查失败',
            description: ['错误：开始事件节点后面有且只有一个节点']
          });
          
          stepStatus.value = 'error';
          flowStepsCurrent.value++;
          
          // 添加后续节点为未检查状态
          const subsequentNodes = getSubsequentNodes(startTask, elementRegistry);
          subsequentNodes.forEach(item => {
            flowSteps.value.push({
              title: item.businessObject.name || item.id,
              description: ['检查未开始']
            });
          });
        } else {
          // 正常流程：继续检查后续节点
          if (firstUserTask.length === 0) {
            addCheckResult({
              type: 'error',
              message: '开始节点后未找到用户任务节点',
              elementId: startTask.id,
              elementName: startTask.businessObject.name || '开始节点'
            });
          } else {
            // 开始遍历后续节点
            getNextNodeStep(firstUserTask[0], elementRegistry);
          }
          
          // 添加结束步骤
          flowSteps.value.push({
            title: '结束',
            description: [`流程检查完成：共发现 ${totalErrors.value} 个错误，${totalWarnings.value} 个警告`]
          });
          
          if (totalErrors.value > 0) {
            stepStatus.value = 'error';
          } else if (totalWarnings.value > 0) {
            stepStatus.value = 'warning';
          } else {
            stepStatus.value = 'success';
          }
        }

        if (totalErrors.value > 0) {
          message.warning(`发现 ${totalErrors.value} 个错误，${totalWarnings.value} 个警告`);
        } else if (totalWarnings.value > 0) {
          message.info(`发现 ${totalWarnings.value} 个警告`);
        } else {
          message.success('流程检查通过，未发现问题');
        }
        
        props.onCheckComplete(checkResults.value);
      } catch (error: any) {
        console.error('流程检查失败:', error);
        message.error(error.message || '流程检查失败');
        
        flowSteps.value.push({
          title: '检查失败',
          description: [error.message || '流程检查失败']
        });
        
        stepStatus.value = 'error';
        flowStepsCurrent.value++;
      } finally {
        loading.value = false;
      }
    };
    
    // 打开流程检查窗口
    const openCheckModal = () => {
      visible.value = true;
      runProcessCheck();
    };
    
    // 关闭窗口
    const closeModal = () => {
      visible.value = false;
    };
    
    return () => (
      <>
        <Button
          ghost
          type="primary"
          icon={<CheckCircleOutlined />}
          onClick={openCheckModal}
        >
          流程检查
        </Button>
        
        {/* 检查结果弹窗 */}
        <Modal
          title={
            <Space>
              <CheckCircleOutlined />
              流程检查结果
              <Space size={8}>
                <Tag color="red">{`错误: ${totalErrors.value}`}</Tag>
                <Tag color="orange">{`警告: ${totalWarnings.value}`}</Tag>
                <Tag color="blue">{`提示: ${totalInfos.value}`}</Tag>
              </Space>
            </Space>
          }
          visible={visible.value}
          onCancel={closeModal}
          footer={[
            <Button key="close" onClick={closeModal}>
              关闭
            </Button>
          ]}
          width={900}
          destroyOnClose
        >
          <div>
            {/* 步骤展示 */}
            <Steps 
              current={flowStepsCurrent.value}
              status={stepStatus.value}
              direction="vertical"
              size="small"
            >
              {flowSteps.value.map((step, index) => (
                <Steps.Step 
                  key={index}
                  title={step.title}
                  description={step.description.map((desc, i) => (
                    <div key={i}>{desc}</div>
                  ))}
                />
              ))}
            </Steps>
            
            {/* 错误列表 */}
            {checkResults.value.length > 0 && (
              <div style={{ marginTop: '20px' }}>
                <h3>详细检查结果</h3>
                <Table
                  columns={columns}
                  dataSource={checkResults.value}
                  bordered
                  pagination={false}
                  rowKey="id"
                />
              </div>
            )}
          </div>
        </Modal>
      </>
    );
  }
});